<template>
  <div id="particles-js" class="login">

    <div style="position: fixed;background: rgba(216,239,246,0.9); top: 50%; left: 50%;width: 400px;transform: translate(-50%, -50%);box-shadow: 0px 15px 25px rgba(0, 0, 0, .5);border-radius: 15px;">


      <div style="flex: 1;">
        <el-form ref="loginRef" :rules="rules" :model="user" style="width: 300px;margin: 0 auto;">
          <h2 align="center">欢迎来到后台登录页面</h2>
          <el-form-item prop="username">
            <el-input prefix-icon="User" size="large" placeholder="请输入账号" v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" show-password size="large" placeholder="请输入密码" v-model="user.password">
              <template #prefix>
                <img class="imgInpIcon" :src="require('@/assets/imgs/inpIcon/pwdInp.png')" alt="">
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="phone" v-if="loginOrRegister === '注册'">
            <el-input size="large" placeholder="请输入手机号" v-model="user.phone">
              <template #prefix>
                <img class="imgInpIcon" :src="require('@/assets/imgs/inpIcon/phoneInp.png')" alt="">
              </template>
            </el-input>
          </el-form-item>
          <div style="display: flex">
            <div v-if="loginOrRegister === '登录'" style="flex: 1;color: #79bbff;cursor: pointer" @click="loginOrRegisterFun('注册')">注册</div>
            <div v-else style="flex: 1;color: #0f9876;cursor: pointer" @click="loginOrRegisterFun('登录')">登录</div>
            <div style="flex: 1; text-align: right" @click="forgetPwdDialog"><span style="color: #1cc098; cursor: pointer">忘记密码</span></div>
          </div>
          <el-form-item style="margin-top: 10px">
            <el-button :loading="load" v-if="loginOrRegister === '登录'" type="primary" style="width: 100%;" @click="login">登录</el-button>
            <el-button :loading="load" v-if="loginOrRegister === '注册'" type="success" style="width: 100%;" @click="register">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>



    <!--忘记密码-->
    <el-dialog
        v-model="dialogForget"
        title="忘记密码"
        width="30%"
        :close-on-click-modal="false"
    >
      <el-form ref="dialogRef" :rules="rules" :model="dialogForm" style="width: 80%;margin: 20px auto">
        <el-form-item prop="username">
          <el-input prefix-icon="User" size="large" placeholder="请输入账号" v-model="dialogForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input size="large" placeholder="请输入手机号" v-model="dialogForm.phone">
            <template #prefix>
              <img class="imgInpIcon" :src="require('@/assets/imgs/inpIcon/phoneInp.png')" alt="">
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="large" placeholder="请输入密码" v-model="dialogForm.password">
            <template #prefix>
              <img class="imgInpIcon" :src="require('@/assets/imgs/inpIcon/pwdInp.png')" alt="">
            </template>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-top: 10px">
          <el-button :loading="load" type="warning" style="width: 100%;" @click="forgetPwd">重置密码</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="js" setup>
import {ref, reactive, getCurrentInstance, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {activeRouter} from "@/utils/perm";
import setParticles from '@/utils/setPartcles'

onMounted(() => {
  particlesJS('particles-js', setParticles);
});

const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('手机号不能为空'));
  }
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的11位手机号码'));
  }
  callback();
};

/*变量*/
const {proxy} = getCurrentInstance()
let user = reactive({
  username: 'admin',
  password: 'admin',
});
let dialogForm = reactive({});
let rules = reactive({
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
  phone: [
    {validator: checkPhone, trigger: 'blur'},
  ],
})
let loginOrRegister = ref('登录');
let load = ref(false);
let dialogForget = ref(false);
/*方法*/
// 切换登录注册功能
const loginOrRegisterFun = (val) => {
  loginOrRegister.value = val;
  console.log(loginOrRegister);
};

// 重置表单功能
let resetForm = (formData)=>{
  formData.username = '';
  formData.password = '';
  formData.phone = '';
}

// 登录
let login = () => {
  proxy.$refs['loginRef'].validate(valid => {
    if (valid) {
      load.value = true
      proxy.$request.post('user/login',JSON.stringify(user)).then(res => {
        if (res.code === '200') {
          sessionStorage.setItem('user-data',JSON.stringify(res.data));
          ElMessage({message: '登录成功！', type: "success"});
          load.value = false;
          const permList = res.data.permList;
          activeRouter(permList);
          setTimeout(() => {
            // 1秒后，执行这里的代码
            proxy.$router.push('/');
          }, 100);
        } else {
          ElMessage({message: res.msg, type: "error"});
          load.value = false;
        }
      });
    }
  });
};
// 注册
let register = () => {
  proxy.$refs['loginRef'].validate(valid => {
    if (valid) {
      load.value = true
      proxy.$request.post('user/register', JSON.stringify(user)).then(res => {
        if (res.code === '200') {
          ElMessage({message: '注册成功！', type: "success"});
          loginOrRegisterFun('登录');
          resetForm(user); // 重置表单内容
          load.value = false;
        } else {
          ElMessage({message: res.msg, type: "error"});
          load.value = false;
        }
      });
    }
  });
};
// 忘记密码
let forgetPwdDialog = () => {
  resetForm(dialogForm)
  dialogForget.value = true;
}
let forgetPwd = () => {
  proxy.$refs['dialogRef'].validate(valid => {
    if (valid) {
      load.value = true
      proxy.$request.post('user/forgetPwd', JSON.stringify(dialogForm)).then(res => {
        if (res.code === '200') {
          ElMessageBox.alert('<p style="color: #0f9876;margin-left: 20px">重置成功！密码为：' + dialogForm.password + '</p>', '提示', {
            confirmButtonText: 'OK',
            dangerouslyUseHTMLString: true,
          });
          dialogForget.value = false;
        } else {
          ElMessage({message: res.msg, type: "error"});
        }
        load.value = false
      });
    }
  });
};
</script>

<style>
.login{
  height: 100%;
  width: 100%;
  background-image: url('@/assets/animalcrossing.jpg');
  background-size: cover;

  opacity: 0.9;
  position: fixed;
  background-repeat: no-repeat;
}

body {
  height: 100%;
  margin: 0;
  padding: 0;
}
</style>